package com.edg.controller;


import com.edg.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;

    @RequestMapping("/all")
    public List<User> listUser(){
        return service.listUser();
    }

    @RequestMapping("/update")
    public int update(User user){
        return service.update(user);
    }

    @RequestMapping("/delete")
    public int delete(Long id){
        return service.delete(id);
    }

    @RequestMapping("/findUserById")
    public User getUserById(Long id){
        User user = service.findUserById(id);
        return user;
    }

    @RequestMapping("/page")
    public Page<User> pageInfo(Integer page,Integer size){
        PageHelper.startPage(page,size);
        Page<User> pageInfo = (Page<User>) service.listUser();
        return pageInfo;
    }

    //用户注册
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user,@RequestParam("code") String code,@RequestParam("phone") String phone){
        User user1 = service.findUserByPhone(phone);
        if (user1!=null){
            return null;
        }
        sandCode(phone);
        service.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //发送验证码
    @PostMapping("sandCode")
    public ResponseEntity<Void> sandCode(@RequestParam("phone") String phone){
        service.sendCode(phone);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

}
